home *** CD-ROM | disk | FTP | other *** search
/ Aminet 34 / Aminet 34 (2000)(Schatztruhe)[!][Dec 1999].iso / Aminet / util / gnu / unixcmds.lha / unixcmds / src / grep-2.1 / grep.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-10-06  |  24.7 KB  |  1,013 lines

  1. /* grep.c - main driver file for grep.
  2.    Copyright (C) 1992, 1997 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  17.    02111-1307, USA.  */
  18.  
  19. /* Written July 1992 by Mike Haertel.  */
  20.  
  21. #ifdef HAVE_CONFIG_H
  22. # include <config.h>
  23. #endif
  24. #include <sys/types.h>
  25. #include <sys/stat.h>
  26. #if defined(HAVE_MMAP)
  27. # include <sys/mman.h>
  28. #endif
  29. #if defined(HAVE_SETRLIMIT)
  30. # include <sys/time.h>
  31. # include <sys/resource.h>
  32. #endif
  33. #include <stdio.h>
  34. #include "system.h"
  35. #include "getopt.h"
  36. #include "getpagesize.h"
  37. #include "grep.h"
  38.  
  39. #include "amigawildcard.h"
  40.  
  41. #undef MAX
  42. #define MAX(A,B) ((A) > (B) ? (A) : (B))
  43.  
  44. /* if non-zero, display usage information and exit */
  45. static int show_help;
  46.  
  47. /* If non-zero, print the version on standard output and exit.  */
  48. static int show_version;
  49.  
  50. /* Long options equivalences. */
  51. static struct option long_options[] =
  52. {
  53.   {"after-context", required_argument, NULL, 'A'},
  54.   {"basic-regexp", no_argument, NULL, 'G'},
  55.   {"before-context", required_argument, NULL, 'B'},
  56.   {"byte-offset", no_argument, NULL, 'b'},
  57.   {"context", no_argument, NULL, 'C'},
  58.   {"count", no_argument, NULL, 'c'},
  59.   {"extended-regexp", no_argument, NULL, 'E'},
  60.   {"file", no_argument, NULL, 'f'},
  61.   {"files-without-match", no_argument, NULL, 'L'},
  62.   {"fixed-regexp", no_argument, NULL, 'F'},
  63.   {"help", no_argument, &show_help, 1},
  64.   {"ignore-case", no_argument, NULL, 'i'},
  65.   {"line-number", no_argument, NULL, 'n'},
  66.   {"line-regexp", no_argument, NULL, 'x'},
  67.   {"no-filename", no_argument, NULL, 'h'},
  68.   {"no-messages", no_argument, NULL, 's'},
  69.   {"quiet", no_argument, NULL, 'q'},
  70.   {"regexp", no_argument, NULL, 'e'},
  71.   {"revert-match", no_argument, NULL, 'v'},
  72.   {"silent", no_argument, NULL, 'q'},
  73. #if O_BINARY
  74.   {"binary", no_argument, NULL, 'U'},
  75.   {"unix-byte-offsets", no_argument, NULL, 'u'},
  76. #endif
  77.   {"version", no_argument, NULL, 'V'},
  78.   {"word-regexp", no_argument, NULL, 'w'},
  79.   {0, 0, 0, 0}
  80. };
  81.  
  82. /* Define flags declared in grep.h. */
  83. char *matcher;
  84. int match_icase;
  85. int match_words;
  86. int match_lines;
  87.  
  88. /* For error messages. */
  89. static char *prog;
  90. static char *filename;
  91. static int errseen;
  92.  
  93. static void usage PARAMS((int));
  94. static void error PARAMS((const char *, int));
  95. static int  setmatcher PARAMS((char *));
  96. static void reset PARAMS((int));
  97. static int  fillbuf PARAMS((size_t));
  98. static int  grepbuf PARAMS((char *, char *));
  99. static void prtext PARAMS((char *, char *, int *));
  100. static void prpending PARAMS((char *));
  101. static void prline PARAMS((char *, char *, int));
  102. static void nlscan PARAMS((char *));
  103. static int  grep PARAMS((int));
  104.  
  105. /* Functions we'll use to search. */
  106. static void (*compile) PARAMS((char *, size_t));
  107. static char *(*execute) PARAMS((char *, size_t, char **));
  108.  
  109. /* Print a message and possibly an error string.  Remember
  110.    that something awful happened. */
  111. static void
  112. error(mesg, errnum)
  113.      const char *mesg;
  114.      int errnum;
  115. {
  116.   if (errnum)
  117.     fprintf(stderr, "%s: %s: %s\n", prog, mesg, strerror(errnum));
  118.   else
  119.     fprintf(stderr, "%s: %s\n", prog, mesg);
  120.   errseen = 1;
  121. }
  122.  
  123. /* Like error(), but die horribly after printing. */
  124. void
  125. fatal(mesg, errnum)
  126.      const char *mesg;
  127.      int errnum;
  128. {
  129.   error(mesg, errnum);
  130.   exit(2);
  131. }
  132.  
  133. /* Interface to handle errors and fix library lossage. */
  134. char *
  135. xmalloc(size)
  136.      size_t size;
  137. {
  138.   char *result;
  139.  
  140.   result = malloc(size);
  141.   if (size && !result)
  142.     fatal(_("memory exhausted"), 0);
  143.   return result;
  144. }
  145.  
  146. /* Interface to handle errors and fix some library lossage. */
  147. char *
  148. xrealloc(ptr, size)
  149.      char *ptr;
  150.      size_t size;
  151. {
  152.   char *result;
  153.  
  154.   if (ptr)
  155.     result = realloc(ptr, size);
  156.   else
  157.     result = malloc(size);
  158.   if (size && !result)
  159.     fatal(_("memory exhausted"), 0);
  160.   return result;
  161. }
  162.  
  163. /* Hairy buffering mechanism for grep.  The intent is to keep
  164.    all reads aligned on a page boundary and multiples of the
  165.    page size. */
  166.  
  167. static char *buffer;        /* Base of buffer. */
  168. static size_t bufsalloc;    /* Allocated size of buffer save region. */
  169. static size_t bufalloc;        /* Total buffer size. */
  170. static int bufdesc;        /* File descriptor. */
  171. static char *bufbeg;        /* Beginning of user-visible stuff. */
  172. static char *buflim;        /* Limit of user-visible stuff. */
  173.  
  174. #if defined(HAVE_MMAP)
  175. static int bufmapped;        /* True for ordinary files. */
  176. static struct stat bufstat;    /* From fstat(). */
  177. static off_t bufoffset;        /* What read() normally remembers. */
  178. #endif
  179.  
  180. /* Reset the buffer for a new file.  Initialize
  181.    on the first time through. */
  182. static void
  183. reset(fd)
  184.      int fd;
  185. {
  186.   static int initialized;
  187.  
  188.   if (!initialized)
  189.     {
  190.       initialized = 1;
  191. #ifndef BUFSALLOC
  192.       bufsalloc = MAX(8192, getpagesize());
  193. #else
  194.       bufsalloc = BUFSALLOC;
  195. #endif
  196.       bufalloc = 5 * bufsalloc;
  197.       /* The 1 byte of overflow is a kludge for dfaexec(), which
  198.      inserts a sentinel newline at the end of the buffer
  199.      being searched.  There's gotta be a better way... */
  200.       buffer = valloc(bufalloc + 1);
  201.       if (!buffer)
  202.     fatal(_("memory exhausted"), 0);
  203.       bufbeg = buffer;
  204.       buflim = buffer;
  205.     }
  206.   bufdesc = fd;
  207. #if defined(HAVE_MMAP)
  208.   if (fstat(fd, &bufstat) < 0 || !S_ISREG(bufstat.st_mode))
  209.     bufmapped = 0;
  210.   else
  211.     {
  212.       bufmapped = 1;
  213.       bufoffset = lseek(fd, 0, 1);
  214.     }
  215. #endif
  216. }
  217.  
  218. /* Read new stuff into the buffer, saving the specified
  219.    amount of old stuff.  When we're done, 'bufbeg' points
  220.    to the beginning of the buffer contents, and 'buflim'
  221.    points just after the end.  Return count of new stuff. */
  222. static int
  223. fillbuf(save)
  224.      size_t save;
  225. {
  226.   char *nbuffer, *dp, *sp;
  227.   int cc;
  228. #if defined(HAVE_MMAP)
  229.   caddr_t maddr;
  230. #endif
  231.   static int pagesize;
  232.  
  233.   if (pagesize == 0 && (pagesize = getpagesize()) == 0)
  234.     abort();
  235.  
  236.   if (save > bufsalloc)
  237.     {
  238.       while (save > bufsalloc)
  239.     bufsalloc *= 2;
  240.       bufalloc = 5 * bufsalloc;
  241.       nbuffer = valloc(bufalloc + 1);
  242.       if (!nbuffer)
  243.     fatal(_("memory exhausted"), 0);
  244.     }
  245.   else
  246.     nbuffer = buffer;
  247.  
  248.   sp = buflim - save;
  249.   dp = nbuffer + bufsalloc - save;
  250.   bufbeg = dp;
  251.   while (save--)
  252.     *dp++ = *sp++;
  253.  
  254.   /* We may have allocated a new, larger buffer.  Since
  255.      there is no portable vfree(), we just have to forget
  256.      about the old one.  Sorry. */
  257.   buffer = nbuffer;
  258.  
  259. #if defined(HAVE_MMAP)
  260.   if (bufmapped && bufoffset % pagesize == 0
  261.       && bufstat.st_size - bufoffset >= bufalloc - bufsalloc)
  262.     {
  263.       maddr = buffer + bufsalloc;
  264.       maddr = mmap(maddr, bufalloc - bufsalloc, PROT_READ | PROT_WRITE,
  265.            MAP_PRIVATE | MAP_FIXED, bufdesc, bufoffset);
  266.       if (maddr == (caddr_t) -1)
  267.     {
  268.       fprintf(stderr, _("%s: warning: %s: %s\n"), prog, filename,
  269.           strerror(errno));
  270.       goto tryread;
  271.     }
  272. #if 0
  273.       /* You might thing this (or MADV_WILLNEED) would help,
  274.      but it doesn't, at least not on a Sun running 4.1.
  275.      In fact, it actually slows us down about 30%! */
  276.       madvise(maddr, bufalloc - bufsalloc, MADV_SEQUENTIAL);
  277. #endif
  278.       cc = bufalloc - bufsalloc;
  279.       bufoffset += cc;
  280.     }
  281.   else
  282.     {
  283.     tryread:
  284.       /* We come here when we're not going to use mmap() any more.
  285.      Note that we need to synchronize the file offset the
  286.      first time through. */
  287.       if (bufmapped)
  288.     {
  289.       bufmapped = 0;
  290.       lseek(bufdesc, bufoffset, 0);
  291.     }
  292.       cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  293.     }
  294. #else
  295.   cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  296. #endif
  297. #if O_BINARY
  298.   if (O_BINARY && cc > 0)
  299.     cc = undossify_input(buffer + bufsalloc, cc);
  300. #endif
  301.   if (cc > 0)
  302.     buflim = buffer + bufsalloc + cc;
  303.   else
  304.     buflim = buffer + bufsalloc;
  305.   return cc;
  306. }
  307.  
  308. /* Flags controlling the style of output. */
  309. static int out_quiet;        /* Suppress all normal output. */
  310. static int out_invert;        /* Print nonmatching stuff. */
  311. static int out_file;        /* Print filenames. */
  312. static int out_line;        /* Print line numbers. */
  313. static int out_byte;        /* Print byte offsets. */
  314. static int out_before;        /* Lines of leading context. */
  315. static int out_after;        /* Lines of trailing context. */
  316.  
  317. /* Internal variables to keep track of byte count, context, etc. */
  318. static size_t totalcc;        /* Total character count before bufbeg. */
  319. static char *lastnl;        /* Pointer after last newline counted. */
  320. static char *lastout;        /* Pointer after last character output;
  321.                    NULL if no character has been output
  322.                    or if it's conceptually before bufbeg. */
  323. static size_t totalnl;        /* Total newline count before lastnl. */
  324. static int pending;        /* Pending lines of output. */
  325. static int done_on_match;        /* Stop scanning file on first match */
  326.  
  327. #if O_BINARY
  328. # include "dosbuf.c"
  329. #endif
  330.  
  331. static void
  332. nlscan(lim)
  333.      char *lim;
  334. {
  335.   char *beg;
  336.  
  337.   for (beg = lastnl; beg < lim; ++beg)
  338.     if (*beg == '\n')
  339.       ++totalnl;
  340.   lastnl = beg;
  341. }
  342.  
  343. static void
  344. prline(beg, lim, sep)
  345.      char *beg;
  346.      char *lim;
  347.      int sep;
  348. {
  349.   if (out_file)
  350.     printf("%s%c", filename, sep);
  351.   if (out_line)
  352.     {
  353.       nlscan(beg);
  354.       printf("%u%c", (unsigned int)++totalnl, sep);
  355.       lastnl = lim;
  356.     }
  357.   if (out_byte)
  358. #if O_BINARY
  359.     printf("%lu%c",
  360.        (unsigned long int) dossified_pos(totalcc + (beg - bufbeg)), sep);
  361. #else
  362.     printf("%lu%c", (unsigned long int) (totalcc + (beg - bufbeg)), sep);
  363. #endif
  364.   fwrite(beg, 1, lim - beg, stdout);
  365.   if (ferror(stdout))
  366.     error(_("writing output"), errno);
  367.   lastout = lim;
  368. }
  369.  
  370. /* Print pending lines of trailing context prior to LIM. */
  371. static void
  372. prpending(lim)
  373.      char *lim;
  374. {
  375.   char *nl;
  376.  
  377.   if (!lastout)
  378.     lastout = bufbeg;
  379.   while (pending > 0 && lastout < lim)
  380.     {
  381.       --pending;
  382.       if ((nl = memchr(lastout, '\n', lim - lastout)) != 0)
  383.     ++nl;
  384.       else
  385.     nl = lim;
  386.       prline(lastout, nl, '-');
  387.     }
  388. }
  389.  
  390. /* Print the lines between BEG and LIM.  Deal with context crap.
  391.    If NLINESP is non-null, store a count of lines between BEG and LIM. */
  392. static void
  393. prtext(beg, lim, nlinesp)
  394.      char *beg;
  395.      char *lim;
  396.      int *nlinesp;
  397. {
  398.   static int used;        /* avoid printing "--" before any output */
  399.   char *bp, *p, *nl;
  400.   int i, n;
  401.  
  402.   if (!out_quiet && pending > 0)
  403.     prpending(beg);
  404.  
  405.   p = beg;
  406.  
  407.   if (!out_quiet)
  408.     {
  409.       /* Deal with leading context crap. */
  410.  
  411.       bp = lastout ? lastout : bufbeg;
  412.       for (i = 0; i < out_before; ++i)
  413.     if (p > bp)
  414.       do
  415.         --p;
  416.       while (p > bp && p[-1] != '\n');
  417.  
  418.       /* We only print the "--" separator if our output is
  419.      discontiguous from the last output in the file. */
  420.       if ((out_before || out_after) && used && p != lastout)
  421.     puts("--");
  422.  
  423.       while (p < beg)
  424.     {
  425.       nl = memchr(p, '\n', beg - p);
  426.       prline(p, nl + 1, '-');
  427.       p = nl + 1;
  428.     }
  429.     }
  430.  
  431.   if (nlinesp)
  432.     {
  433.       /* Caller wants a line count. */
  434.       for (n = 0; p < lim; ++n)
  435.     {
  436.       if ((nl = memchr(p, '\n', lim - p)) != 0)
  437.         ++nl;
  438.       else
  439.         nl = lim;
  440.       if (!out_quiet)
  441.         prline(p, nl, ':');
  442.       p = nl;
  443.     }
  444.       *nlinesp = n;
  445.     }
  446.   else
  447.     if (!out_quiet)
  448.       prline(beg, lim, ':');
  449.  
  450.   pending = out_after;
  451.   used = 1;
  452. }
  453.  
  454. /* Scan the specified portion of the buffer, matching lines (or
  455.    between matching lines if OUT_INVERT is true).  Return a count of
  456.    lines printed. */
  457. static int
  458. grepbuf(beg, lim)
  459.      char *beg;
  460.      char *lim;
  461. {
  462.   int nlines, n;
  463.   register char *p, *b;
  464.   char *endp;
  465.  
  466.   nlines = 0;
  467.   p = beg;
  468.   while ((b = (*execute)(p, lim - p, &endp)) != 0)
  469.     {
  470.       /* Avoid matching the empty line at the end of the buffer. */
  471.       if (b == lim && ((b > beg && b[-1] == '\n') || b == beg))
  472.     break;
  473.       if (!out_invert)
  474.     {
  475.       prtext(b, endp, (int *) 0);
  476.       nlines += 1;
  477.       if (done_on_match)
  478.         return nlines;
  479.     }
  480.       else if (p < b)
  481.     {
  482.       prtext(p, b, &n);
  483.       nlines += n;
  484.     }
  485.       p = endp;
  486.     }
  487.   if (out_invert && p < lim)
  488.     {
  489.       prtext(p, lim, &n);
  490.       nlines += n;
  491.     }
  492.   return nlines;
  493. }
  494.  
  495. /* Search a given file.  Return a count of lines printed. */
  496. static int
  497. grep(fd)
  498.      int fd;
  499. {
  500.   int nlines, i;
  501.   size_t residue, save;
  502.   char *beg, *lim;
  503.  
  504.   reset(fd);
  505.  
  506.   totalcc = 0;
  507.   lastout = 0;
  508.   totalnl = 0;
  509.   pending = 0;
  510.  
  511.   nlines = 0;
  512.   residue = 0;
  513.   save = 0;
  514.  
  515.   for (;;)
  516.     {
  517.       if (fillbuf(save) < 0)
  518.     {
  519.       error(filename, errno);
  520.       return nlines;
  521.     }
  522.       lastnl = bufbeg;
  523.       if (lastout)
  524.     lastout = bufbeg;
  525.       if (buflim - bufbeg == save)
  526.     break;
  527.       beg = bufbeg + save - residue;
  528.       for (lim = buflim; lim > beg && lim[-1] != '\n'; --lim)
  529.     ;
  530.       residue = buflim - lim;
  531.       if (beg < lim)
  532.     {
  533.       nlines += grepbuf(beg, lim);
  534.       if (pending)
  535.         prpending(lim);
  536.       if (nlines && done_on_match && !out_invert)
  537.         return nlines;
  538.     }
  539.       i = 0;
  540.       beg = lim;
  541.       while (i < out_before && beg > bufbeg && beg != lastout)
  542.     {
  543.       ++i;
  544.       do
  545.         --beg;
  546.       while (beg > bufbeg && beg[-1] != '\n');
  547.     }
  548.       if (beg != lastout)
  549.     lastout = 0;
  550.       save = residue + lim - beg;
  551.       totalcc += buflim - bufbeg - save;
  552.       if (out_line)
  553.     nlscan(beg);
  554.     }
  555.   if (residue)
  556.     {
  557.       nlines += grepbuf(bufbeg + save - residue, buflim);
  558.       if (pending)
  559.     prpending(buflim);
  560.     }
  561.   return nlines;
  562. }
  563.  
  564.  
  565. static void
  566. usage(status)
  567. int status;
  568. {
  569.   if (status != 0)
  570.     {
  571.       fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"), prog);
  572.       fprintf (stderr, _("Try `%s --help' for more information.\n"), prog);
  573.     }
  574.   else
  575.     {
  576.       printf (_("Usage: %s [OPTION]... PATTERN [FILE] ...\n"), prog);
  577.       printf ("\n");
  578.       printf (_("Regexp selection and interpretation:\n"));
  579.       printf (_("  -E, --extended-regexp     PATTERN is an extended regular expression\n"));
  580.       printf (_("  -F, --fixed-strings       PATTERN is a fixed string separated by newlines\n"));
  581.       printf (_("  -G, --basic-regexp        PATTERN is a basic regular expression\n"));
  582.       printf (_("  -e, --regexp=PATTERN      use PATTERN as a regular expression\n"));
  583.       printf (_("  -f, --file=FILE         obtain PATTERN from FILE\n"));
  584.       printf (_("  -i, --ignore-case         ignore case distinctions\n"));
  585.       printf (_("  -w, --word-regexp         force PATTERN to match only whole words\n"));
  586.       printf (_("  -x, --line-regexp         force PATTERN to match only whole lines\n"));
  587.       printf ("\n");
  588.       printf (_("Miscellaneous:\n"));
  589.       printf (_("  -s, --no-messages         suppress error messages\n"));
  590.       printf (_("  -v, --revert-match        select non-matching lines\n"));
  591.       printf (_("  -V, --version             print version information and exit\n"));
  592.       printf (_("      --help                display this help and exit\n"));
  593.       printf ("\n");
  594.       printf (_("Output control:\n"));
  595.       printf (_("  -b, --byte-offset         print the byte offset with output lines\n"));
  596.       printf (_("  -n, --line-number         print line number with output lines\n"));
  597.       printf (_("  -H, --with-filename       print the filename for each match\n"));
  598.       printf (_("  -h, --no-filename         suppress the prefixing filename on ouput\n"));
  599.       printf (_("  -q, --quiet, --silent     suppress all normal output\n"));
  600.       printf (_("  -L, --files-without-match only print FILE names containing no match\n"));
  601.       printf (_("  -l, --files-with-matches  only print FILE names containing matches\n"));
  602.       printf (_("  -c, --count               only print a count of matching lines per FILE\n"));
  603.       printf ("\n");
  604.       printf (_("Context control:\n"));
  605.       printf (_("  -B, --before-context=NUM  print NUM lines of leading context\n"));
  606.       printf (_("  -A, --after-context=NUM   print NUM lines of trailing context\n"));
  607.       printf (_("  -NUM                      same as both -B NUM and -A NUM\n"));
  608.       printf (_("  -C, --context             same as -2\n"));
  609. #if O_BINARY
  610.       printf (_("  -U, --binary              do not strip CR characters at EOL\n"));
  611.       printf (_("  -u, --unix-byte-offsets   report offsets as if CRs were not there\n"));
  612. #endif
  613.       printf ("\n");
  614.       printf (_("There should be one and only one PATTERN, `-e PATTERN' or `-f FILE'.\n"));
  615.       printf (_("If call as `egrep', this implies -E and `fgrep' for -F.\n"));
  616.       printf (_("If no -[GEF], then -G is assumed.\n"));
  617.       printf ("\n");
  618.       printf (_("Report bugs to <bug-gnu-utils@prep.ai.mit.edu>.\n"));
  619.     }
  620.   exit(status);
  621. }
  622.  
  623. /* Go through the matchers vector and look for the specified matcher.
  624.    If we find it, install it in compile and execute, and return 1.  */
  625. static int
  626. setmatcher(name)
  627.      char *name;
  628. {
  629.   int i;
  630. #ifdef HAVE_SETRLIMIT
  631.   struct rlimit rlim;
  632. #endif
  633.  
  634.   for (i = 0; matchers[i].name; ++i)
  635.     if (strcmp(name, matchers[i].name) == 0)
  636.       {
  637.     compile = matchers[i].compile;
  638.     execute = matchers[i].execute;
  639. #if HAVE_SETRLIMIT && defined(RLIMIT_STACK)
  640.     /* I think every platform needs to do this, so that regex.c
  641.        doesn't oveflow the stack.  The default value of
  642.        `re_max_failures' is too large for some platforms: it needs
  643.        more than 3MB-large stack.
  644.  
  645.        The test for HAVE_SETRLIMIT should go into `configure'.  */
  646.     if (!getrlimit (RLIMIT_STACK, &rlim))
  647.       {
  648.         long newlim;
  649.         extern long int re_max_failures; /* from regex.c */
  650.  
  651.         /* Approximate the amount regex.c needs, plus some more.  */
  652.         newlim = re_max_failures * 2 * 20 * sizeof (char *);
  653.         if (newlim > rlim.rlim_max)
  654.           {
  655.         newlim = rlim.rlim_max;
  656.         re_max_failures = newlim / (2 * 20 * sizeof (char *));
  657.           }
  658.         if (rlim.rlim_cur < newlim)
  659.           rlim.rlim_cur = newlim;
  660.  
  661.         setrlimit (RLIMIT_STACK, &rlim);
  662.       }
  663. #endif
  664.     return 1;
  665.       }
  666.   return 0;
  667. }
  668.  
  669. int
  670. main(argc, argv)
  671.      int argc;
  672.      char *argv[];
  673. {
  674.   char *keys;
  675.   size_t keycc, oldcc, keyalloc;
  676.   int keyfound, count_matches, no_filenames, list_files, suppress_errors;
  677.   int with_filenames;
  678.   int opt, cc, desc, count, status, argstart;
  679.   FILE *fp;
  680.   extern char *optarg;
  681.   extern int optind;
  682.   t_strlist strl;
  683.   char *infile;
  684.  
  685.   prog = argv[0];
  686.   if (prog && strrchr(prog, '/'))
  687.     prog = strrchr(prog, '/') + 1;
  688.  
  689. #if defined(__MSDOS__) || defined(_WIN32)
  690.   /* DOS and MS-Windows use backslashes as directory separators, and usually
  691.      have an .exe suffix.  They also have case-insensitive filesystems.  */
  692.   if (prog)
  693.     {
  694.       char *p = prog;
  695.       char *bslash = strrchr(argv[0], '\\');
  696.  
  697.       if (bslash && bslash >= prog) /* for mixed forward/backslash case */
  698.     prog = bslash + 1;
  699.       else if (prog == argv[0]
  700.            && argv[0][0] && argv[0][1] == ':') /* "c:progname" */
  701.     prog = argv[0] + 2;
  702.  
  703.       /* Collapse the letter-case, so `strcmp' could be used hence.  */
  704.       for ( ; *p; p++)
  705.     if (*p >= 'A' && *p <= 'Z')
  706.       *p += 'a' - 'A';
  707.  
  708.       /* Remove the .exe extension, if any.  */
  709.       if ((p = strrchr(prog, '.')) && strcmp(p, ".exe") == 0)
  710.     *p = '\0';
  711.     }
  712. #endif
  713.  
  714.   keys = NULL;
  715.   keycc = 0;
  716.   keyfound = 0;
  717.   count_matches = 0;
  718.   no_filenames = 0;
  719.   with_filenames = 0;
  720.   list_files = 0;
  721.   suppress_errors = 0;
  722.   matcher = NULL;
  723.  
  724. /* Internationalization. */
  725. #if HAVE_SETLOCALE
  726.   setlocale (LC_ALL, "");
  727. #endif
  728. #if ENABLE_NLS
  729.   bindtextdomain (PACKAGE, LOCALEDIR);
  730.   textdomain (PACKAGE);
  731. #endif
  732.  
  733.   while ((opt = getopt_long(argc, argv,
  734. #if O_BINARY
  735.          "0123456789A:B:CEFGHVX:bce:f:hiLlnqsvwxyUu",
  736. #else
  737.          "0123456789A:B:CEFGHVX:bce:f:hiLlnqsvwxy",
  738. #endif
  739.          long_options, NULL)) != EOF)
  740.     switch (opt)
  741.       {
  742.       case '0':
  743.       case '1':
  744.       case '2':
  745.       case '3':
  746.       case '4':
  747.       case '5':
  748.       case '6':
  749.       case '7':
  750.       case '8':
  751.       case '9':
  752.     out_before = 10 * out_before + opt - '0';
  753.     out_after = 10 * out_after + opt - '0';
  754.     break;
  755.       case 'A':
  756.     out_after = atoi(optarg);
  757.     if (out_after < 0)
  758.       usage(2);
  759.     break;
  760.       case 'B':
  761.     out_before = atoi(optarg);
  762.     if (out_before < 0)
  763.       usage(2);
  764.     break;
  765.       case 'C':
  766.     out_before = out_after = 2;
  767.     break;
  768.       case 'E':
  769.     if (matcher && strcmp(matcher, "egrep") != 0)
  770.       fatal(_("you may specify only one of -E, -F, or -G"), 0);
  771.     matcher = "posix-egrep";
  772.     break;
  773.       case 'F':
  774.     if (matcher && strcmp(matcher, "fgrep") != 0)
  775.       fatal(_("you may specify only one of -E, -F, or -G"), 0);;
  776.     matcher = "fgrep";
  777.     break;
  778.       case 'G':
  779.     if (matcher && strcmp(matcher, "grep") != 0)
  780.       fatal(_("you may specify only one of -E, -F, or -G"), 0);
  781.     matcher = "grep";
  782.     break;
  783.       case 'H':
  784.     with_filenames = 1;
  785.     break;
  786. #if O_BINARY
  787.       case 'U':
  788.     dos_use_file_type = DOS_BINARY;
  789.     break;
  790.       case 'u':
  791.     dos_report_unix_offset = 1;
  792.     break;
  793. #endif
  794.       case 'V':
  795.     show_version = 1;
  796.     break;
  797.       case 'X':
  798.     if (matcher)
  799.       fatal(_("matcher already specified"), 0);
  800.     matcher = optarg;
  801.     break;
  802.       case 'b':
  803.     out_byte = 1;
  804.     break;
  805.       case 'c':
  806.     out_quiet = 1;
  807.     count_matches = 1;
  808.     break;
  809.       case 'e':
  810.     cc = strlen(optarg);
  811.     keys = xrealloc(keys, keycc + cc + 1 + keyfound);
  812.     if (keyfound)
  813.       keys[keycc++] = '\n';
  814.     strcpy(&keys[keycc], optarg);
  815.     keycc += cc;
  816.     keyfound = 1;
  817.     break;
  818.       case 'f':
  819.     fp = strcmp(optarg, "-") != 0 ? fopen(optarg, "r") : stdin;
  820.     if (!fp)
  821.       fatal(optarg, errno);
  822.     for (keyalloc = 1; keyalloc <= keycc + keyfound; keyalloc *= 2)
  823.       ;
  824.     keys = xrealloc(keys, keyalloc);
  825.     oldcc = keycc;
  826.     if (keyfound)
  827.       keys[keycc++] = '\n';
  828.     while (!feof(fp)
  829.            && (cc = fread(keys + keycc, 1, keyalloc - keycc, fp)) > 0)
  830.       {
  831.         keycc += cc;
  832.         if (keycc == keyalloc)
  833.           keys = xrealloc(keys, keyalloc *= 2);
  834.       }
  835.     if (fp != stdin)
  836.       fclose(fp);
  837.     /* Nuke the final newline to avoid matching a null string. */
  838.     if (keycc - oldcc > 0 && keys[keycc - 1] == '\n')
  839.       --keycc;
  840.     keyfound = 1;
  841.     break;
  842.       case 'h':
  843.     no_filenames = 1;
  844.     break;
  845.       case 'i':
  846.       case 'y':            /* For old-timers . . . */
  847.     match_icase = 1;
  848.     break;
  849.       case 'L':
  850.     /* Like -l, except list files that don't contain matches.
  851.        Inspired by the same option in Hume's gre. */
  852.     out_quiet = 1;
  853.     list_files = -1;
  854.     done_on_match = 1;
  855.     break;
  856.       case 'l':
  857.     out_quiet = 1;
  858.     list_files = 1;
  859.     done_on_match = 1;
  860.     break;
  861.       case 'n':
  862.     out_line = 1;
  863.     break;
  864.       case 'q':
  865.     done_on_match = 1;
  866.     out_quiet = 1;
  867.     break;
  868.       case 's':
  869.     suppress_errors = 1;
  870.     break;
  871.       case 'v':
  872.     out_invert = 1;
  873.     break;
  874.       case 'w':
  875.     match_words = 1;
  876.     break;
  877.       case 'x':
  878.     match_lines = 1;
  879.     break;
  880.       case 0:
  881.     /* long options */
  882.     break;
  883.       default:
  884.     usage(2);
  885.     break;
  886.       }
  887.  
  888.   if (show_version)
  889.     {
  890.       printf (_("grep (GNU grep) %s\n"), VERSION);
  891.       printf ("\n");
  892.       printf (_("\
  893. Copyright (C) 1988, 92, 93, 94, 95, 96, 97 Free Software Foundation, Inc.\n"));
  894.       printf (_("\
  895. This is free software; see the source for copying conditions. There is NO\n\
  896. warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"));
  897.       printf ("\n");
  898.       exit (0);
  899.     }
  900.  
  901.   if (show_help)
  902.     usage(0);
  903.  
  904.   if (!keyfound)
  905.     if (optind < argc)
  906.       {
  907.     keys = argv[optind++];
  908.     keycc = strlen(keys);
  909.       }
  910.     else
  911.       usage(2);
  912.  
  913.   if (!matcher)
  914.     matcher = prog;
  915.  
  916.   if (!setmatcher(matcher) && !setmatcher("default"))
  917.     abort();
  918.  
  919.   (*compile)(keys, keycc);
  920.  
  921.   fill_list(argv,optind,argc,&strl);
  922.   argstart=optind;
  923.  
  924.   if ((strl.len > 1 && !no_filenames) || with_filenames)
  925.     out_file = 1;
  926.  
  927.   status = 1;
  928.  
  929.   if (optind < argstart+strl.len)
  930.     while (optind < argstart+strl.len)
  931.       {
  932.     infile=pop_elt(optind-argstart,&strl);
  933.     
  934.     if (strcmp(infile, "-"))
  935.       {
  936.  
  937.         /* On some platforms `open' will fail for a directory,
  938.            so we stat the file before we attempt to open it.  */
  939.         struct stat st;
  940.  
  941.         
  942.         if (stat (infile, &st) < 0 || S_ISDIR(st.st_mode))
  943.           {
  944.         ++optind;
  945.         continue;
  946.           }
  947.         infile=pop_elt(optind-argstart,&strl);
  948.         desc = open(infile, O_RDONLY);
  949.       }
  950.     else
  951.       desc = 0;
  952.     if (desc < 0)
  953.       {
  954.         if (!suppress_errors)
  955.           error(infile, errno);
  956.       }
  957.     else
  958.       {
  959. #if O_BINARY
  960.         /* Set input to binary mode.  Pipes are simulated with files
  961.            on DOS, so this includes the case of "foo | grep bar".  */
  962.         if (!isatty(desc))
  963.           SET_BINARY(desc);
  964. #endif
  965.         filename = desc == 0 ? _("(standard input)") : infile;
  966.         count = grep(desc);
  967.         if (count_matches)
  968.           {
  969.         if (out_file)
  970.           printf("%s:", filename);
  971.         printf("%d\n", count);
  972.           }
  973.         if (count)
  974.           {
  975.         status = 0;
  976.         if (list_files == 1)
  977.           printf("%s\n", filename);
  978.           }
  979.         else if (list_files == -1)
  980.           printf("%s\n", filename);
  981.       }
  982.     if (desc != 0)
  983.       close(desc);
  984.     ++optind;
  985.       }
  986.   else
  987.     {
  988.       filename = _("(standard input)");
  989. #if O_BINARY
  990.       if (!isatty(0))
  991.     SET_BINARY(0);
  992. #endif
  993.       count = grep(0);
  994.       if (count_matches)
  995.     printf("%d\n", count);
  996.       if (count)
  997.     {
  998.       status = 0;
  999.       if (list_files == 1)
  1000.         printf(_("(standard input)\n"));
  1001.     }
  1002.       else if (list_files == -1)
  1003.     printf(_("(standard input)\n"));
  1004.     }
  1005.  
  1006.   if (fclose (stdout) == EOF)
  1007.     error (_("writing output"), errno);
  1008.  
  1009.   clear_list(&strl);
  1010.  
  1011.   exit(errseen ? 2 : status);
  1012. }
  1013.